//index.js
//获取应用实例
var app = getApp();
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    defaultAvatarUrl: '/images/tukaxiu_logo.png',
    defaultNickName: '您的大名',
    login: true,
    hiddenNo: true,
    topStatus: '',
    nickName: '六六哥',
    userHidden: true,
    userToken: '',
    stickerList: false,
    collecSticherList: [],
    defaltImgHidden: false,
    dataTips: '到底了,亲，╮(￣▽￣")╭'
  },
  onLoad: function() {
    var that = this;
    var userToken = wx.getStorageSync('loginToken')
    console.log('缓存读取的token:' + userToken);
    this.setData({
      token: userToken
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有全局用户信息
      that.setData({
        login: true,
        topStatus: ''
      })
    }
    //载入收藏列表
    var currentUserInfo = this.data.userInfo;
    if (userToken && app.globalData.userInfo) {
      wx.request({
        url: app.globalData.myCollectUrl,
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        data: {
          token: this.data.token,
          p: 1,
        },
        success: function(res) {
          var httpCode = res.statusCode;
          console.log(httpCode);
          if (httpCode != 404 && httpCode != 500 && httpCode != 302) {
            console.log('从屌兄那获取的数据：' + res.data.data);
            that.setData({
              login: false,
              topStatus: 'topStatus2',
              defaultAvatarUrl: currentUserInfo.avatarUrl,
              defaultNickName: currentUserInfo.nickName,
              page: res.data.page, //当前页
              pageTotal: res.data.pagetot, //页数
            })
            //缓存收藏列表
            wx.setStorage({
              key: 'collectStickers',
              data: res.data.data,
            })
            if (res.data.data == '') {
              console.log('空数据');
              that.setData({
                dataTips: '',
                defaltImgHidden: true
              })
            }
          } else if (httpCode == 302) {
            console.log('重新取token');
            wx.showToast({
              title: '请重新登陆',
              icon: 'warn',
            });
            app.wxLogin();
            that.setData({
              login: true,
              topStatus: ''
            })
          } else {
            wx.showToast({
              title: '获取收藏失败',
              icon: 'loading'
            })
          }

        },
        fail: function() {
          console.log('获取收藏列表失败')
        },
        complete: function() {
          console.log('完成收藏求情');
          that.setData({
            collecSticherList: wx.getStorageSync('collectStickers')
          })
        }
      });
    } else {
      console.log('用户还未登录');
    }

  },
  onShow: function() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      console.log('全局用户信息:' + app.globalData.userInfo);
    } else {
      this.setData({
        topStatus: '',
        login: true
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //下拉刷新
  onPullDownRefresh: function() {
    var that = this;
    wx.showNavigationBarLoading();
    wx.request({
      url: app.globalData.myCollectUrl,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: {
        token: this.data.token,
        p: 1,
      },
      success: function(res) {
        wx.hideNavigationBarLoading();
        var httpCode = res.statusCode;
        console.log(httpCode);
        if (httpCode != 404 && httpCode != 500 && httpCode != 302) {
          console.log('从屌兄那获取的数据：' + res.data.data);
          //缓存收藏列表
          wx.setStorage({
            key: 'collectStickers',
            data: res.data.data,
          })
          wx.stopPullDownRefresh();
        } else if (httpCode == 302) {
          app.wxLogin();
          wx.showToast({
            title: '正在登录',
            icon: 'loading'
          });
          wx.showToast({
            title: '再刷一下',
            icon: 'loading'
          });
          wx.stopPullDownRefresh();
        } else {
          wx.showToast({
            title: '服务器出错了',
            icon: 'loading'
          });
          wx.stopPullDownRefresh();
        }
      },
      fail: function() {
        console.log('获取收藏列表失败');
        wx.stopPullDownRefresh();
      },
      complete:function(){
        that.setData({
          collecSticherList: wx.getStorageSync('collectStickers')
        });
      }
    });
  },
  //微信登录
  wxLogin: function(e) {
    var that = this;
    var token = wx.getStorageSync('loginToken')
    wx.getUserInfo({
      success: function(res) {
        //获取信息成功
        app.globalData.userInfo = res.userInfo;
        var currentUserInfo = res.userInfo;
        console.log(res.userInfo);
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        wx.request({
          url: app.globalData.myCollectUrl, //收藏列表接口
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          method: "POST",
          data: {
            token: token,
            nickname: currentUserInfo.avatarUrl,
            avatar: currentUserInfo.nickName,
            p: 1,
          },
          success: function(res) {
            console.log('从屌兄那获取的数据：' + res.data.data)
            var httpCode = res.statusCode;
            if (httpCode != 404 && httpCode != 500) {
              that.setData({
                collecSticherList: res.data.data,
                login: false,
                topStatus: 'topStatus',
                defaultAvatarUrl: currentUserInfo.avatarUrl,
                defaultNickName: currentUserInfo.nickName
              });
              wx.showToast({
                title: '登录中...',
                icon: 'loading',
              })
            } else {
              wx.showToast({
                title: '获取收藏列表失败',
                icon: 'loading'
              })
            }

          },
          fail: function() {
            console.log('获取收藏列表失败');
            wx.showToast({
              title: '授权才可以',
              icon: 'none',
              duration: 500
            })
          }
        });
      },
      fail: function(res) {
        console.log('获取信息失败');
      }
    })
  },
  //查看表情详细
  toStickerDetail: function(e) {
    var that = this;
    var stickerid = e.currentTarget.dataset.stickerid;
    console.log(stickerid);
    wx.navigateTo({
      url: '../sticker_detail/sticker_detail?stickerid=' + stickerid,
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function(options) {
    this.loadMoreSticker();
  },
  //加载更多数据
  loadMoreSticker: function() {
    var that = this;
    var currentPage = this.data.page++;
    var pageTotal = this.data.pageTotal;
    var oldCollecSticherList = this.data.collecSticherList;
    var saveToken = wx.getStorageSync('loginToken');
    this.setData({
      laodHide: false
    });
    //加载当前页面的下一页数据

    if (currentPage <= pageTotal) {
      wx.request({
        url: app.globalData.myCollectUrl,
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        data: {
          token: saveToken,
          p: currentPage + 1,
        },
        success: function(res) {
          //获取失败
          var newCollecSticherList = res.data.data
          that.setData({
            collecSticherList: oldCollecSticherList.concat(newCollecSticherList)
          })
          if (res.statusCode == 500) {
            console.log("获取失败")
            that.setData({
              dataTips: '你还没有收藏 ╮(￣▽￣")╭'
            })
          }
          that.setData({
            laodHide: true
          });
        },
        fail: function() {
          console.log("获取失败");
        }
      });
    } else {
      that.setData({
        dataTips: '到底了亲 ╮(￣▽￣")╭'
      })
    }

  },
  //刷新收藏列表
  getCollectionList() {
    console.log('获取收藏了列表');
    var token = wx.getStorageInfoSync('loginToken');
    if (token && app.globalData.userInfo) {
      wx.request({
        url: app.globalData.myCollectUrl,
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        data: {
          token: token,
          p: 1,
        },
        success: function(res) {
          var httpCode = res.statusCode;
          if (httpCode != 404 && httpCode != 500 && httpCode != 302) {
            console.log('从屌兄那获取的数据：' + res.data.data);
            that.setData({
              login: false,
              topStatus: 'topStatus2',
              defaultAvatarUrl: currentUserInfo.avatarUrl,
              defaultNickName: currentUserInfo.nickName,
              collecSticherList: res.data.data,
              page: res.data.page, //当前页
              pageTotal: res.data.pagetot, //页数
            })
            if (res.data.data == '') {
              console.log('空数据');
              that.setData({
                dataTips: '',
                defaltImgHidden: true
              })
            }
          } else if (httpCode == 302) {
            console.log('重新取token');
            wx.showToast({
              title: '请重新登陆',
              icon: 'warn',
            });
            app.wxLogin();
            that.setData({
              login: true,
              topStatus: ''
            })
          } else {
            wx.showToast({
              title: '获取收藏失败',
              icon: 'loading'
            })
          }

        },
        fail: function() {
          console.log('获取收藏列表失败')
        }
      });
    } else {
      console.log('用户还未登录');
    }
  }
})